//
//  PayNetwork.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/9/9.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "PayNetwork.h"
#import "GFXNetworkHandle.h"
#import <CommonCrypto/CommonDigest.h>

NSString * const AlipayInfo = @"auth/alipay/get/params";//支付宝参数请求
NSString * const WeixinInfo = @"wx/pay/create/pre/payment/order";//微信参数请求
NSString * const CardPayInfo = @"auth/zs/getPayUrl";//招商银行参数请求

@implementation PayNetwork

+ (void)alipayWithParame:(NSDictionary *)parames response:(void (^)(BOOL success,NSString *msg,NSString *orderString))response
{
    [[GFXNetworkHandle shareHandle]post:AlipayInfo params:parames success:^(id json) {
        if ([json[@"status"] isEqualToString:SuccessStatus]) {
            response(YES,json[@"message"],json[@"result"]);
        }else{
            response(NO,json[@"message"],nil);
        }
    } failure:^(NSError *error) {
        response(NO,NetworkError,nil);
    }];
}

+ (void)weixinPayWithParame:(NSDictionary *)parames response:(void (^)(BOOL success,NSString *msg,PayReq *req))response
{
    [[GFXNetworkHandle shareHandle]post:WeixinInfo params:parames success:^(id json) {
        if ([json[@"status"] isEqualToString:SuccessStatus]) {
            NSDictionary *dict = json[@"result"];
            PayReq* req = [[PayReq alloc] init];
            req.timeStamp = [PayNetwork getNowStp];
            req.nonceStr = dict[@"noncestr"];
            req.package = dict[@"package"];
            req.prepayId = dict[@"prepayid"];
            req.partnerId = dict[@"partnerid"];
            
            NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
            [signParams setObject:dict[@"appid"] forKey:@"appid"];
            [signParams setObject:dict[@"noncestr"] forKey:@"noncestr"];
            [signParams setObject:dict[@"package"] forKey:@"package"];
            [signParams setObject:dict[@"partnerid"] forKey:@"partnerid"];
            [signParams setObject:[NSString stringWithFormat:@"%zd",req.timeStamp] forKey:@"timestamp"];
            [signParams setObject:dict[@"prepayid"] forKey:@"prepayid"];
            req.sign = [self createMd5Sign:signParams];
            
            response(YES,json[@"message"],req);
        }else{
            response(NO,json[@"message"],nil);
        }
    } failure:^(NSError *error) {
        response(NO,NetworkError,nil);
    }];
}
+ (void)cardPayWithParame:(NSDictionary *)parames response:(void (^)(BOOL success,NSString *msg,NSString *url))response
{
    [[GFXNetworkHandle shareHandle]post:CardPayInfo params:parames success:^(id json) {
        if ([json[@"status"] isEqualToString:SuccessStatus]) {
            response(YES,json[@"message"],json[@"result"]);
        }else{
            response(NO,json[@"message"],nil);
        }
    } failure:^(NSError *error) {
        response(NO,NetworkError,nil);
    }];
}

#pragma mark ----------------------------微信参数拼接使用------------------
+ (NSTimeInterval)getNowStp
{
    return [[NSDate date] timeIntervalSince1970] * 1000;
}
//微信sign签名
+ (NSString*)createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
    }
    //添加key字段
    [contentString appendFormat:@"key=%@",WeixinSecret];
    //得到MD5 sign签名
    NSString *md5Sign =[PayNetwork md5:contentString];
    return md5Sign;
}
+ (NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}
@end
